package com.jinandi.app.service;


import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jinandi.app.dao.UserDao;
import com.jinandi.app.domain.User;

@Service("userService")
public class UserService extends BaseService implements UserDetailsService {
	
	@Autowired
	private UserDao userDao;//
	
	public int modifyPassword(String password, String name){
		return userDao.modifyPassword(password,name);
	}
	
	public User findByName(String name,String password){
		return userDao.findByName(name,password);
	}
	
	public User findByName2(String name,String password){
		return userDao.findByName2(name,password);
	}
	
	/**
	 * <分页语句>
	 * @return
	 * @author CGC 
	 * 创建日期:2013-4-15 下午5:05:10
	 */
	@Transactional
	public Page<User> findUser(Map<String,Object> params,Map<String ,String> map) {
		Page<User> page= userDao.findAll(new User().getSpecification(params), getPageRequest(map));
		return page;
	}
	
	/**
	 * <根据实体类属性自定义参数查询 详见 Spring DATA JPA>
	 * @param name
	 * @param password
	 * @return
	 * @author CGC 
	 * 创建日期:2013-4-15 下午5:11:20
	 */
	@Transactional
	public List<User> findByNameAndPassword(String name, String password) {
		return userDao.findByNameAndPassword(name, password);
	}

	/**
	 * <自定义语句查询>
	 * @return
	 * @author CGC 
	 * 创建日期:2013-4-15 下午5:10:53
	 */
	@Transactional
	public List<User> findAllUser() {
		return userDao.findAllUser();

	}

	/**
	 * <保存>
	 * @param user
	 * @author CGC 
	 * 创建日期:2013-4-15 下午5:10:17
	 */
	@Transactional
	public void saveUser(User user) {
		userDao.save(user);

	}

	/**
	 * <根据ID查询>
	 * @param id
	 * @return
	 * @author CGC 
	 * 创建日期:2013-4-15 下午5:10:04
	 */
	@Transactional(readOnly = true)
	public User findUserById(Long id) {
		return userDao.findUserById(id);
	}

	/**
	 * <修改>
	 * @param user
	 * @author CGC 
	 * 创建日期:2013-4-15 下午5:09:52
	 */
	@Transactional
	public void updateUser(User user) {
		userDao.save(user);
	}

	/**
	 * <删除>
	 * @param id
	 * @author CGC 
	 * 创建日期:2013-4-15 下午5:09:00
	 */
	@Transactional
	public void deleteUserById(Long id) {
		userDao.deleteUserById(id);
	}

	@SuppressWarnings("deprecation")
	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		List<User> list = userDao.loadUserByUsername(username);
		if(!list.isEmpty()){
			return (UserDetails) list.get(0);
		}else{
			throw new UsernameNotFoundException("未找到该用户!", username);
		}
		
	}

}